package com.mocha.nezha.socket;

import com.corundumstudio.socketio.SocketIOClient;
import com.mocha.nezha.nezha.NezhaClient;
import com.mocha.nezha.nezha.NezhaSessionManager;
import com.mocha.websocket.MochaWebSocketExecutor;
import com.mocha.websocket.handler.MochaSocketCloseHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.Executor;

/**
 * @author: songkui
 * @since: 2024/3/21 0:14
 */
@Slf4j
@Service
public class SocketCloseHandler implements MochaSocketCloseHandler {
    @Override
    public void close(SocketIOClient client) {
        log.info("close channel [sessionId: {}] ", client.getSessionId());

        NezhaClient nezhaClient = NezhaSessionManager.getInstance().getNezhaClient(client.getSessionId().toString());
        if (null != nezhaClient){
            Executor executor = MochaWebSocketExecutor.getInstance().getDisruptor(nezhaClient.getParkCode().hashCode());
            executor = null == executor ? MochaWebSocketExecutor.getInstance().getDefaultExecutor() : executor;
            executor.execute(() -> NezhaSessionManager.getInstance().removeClient(nezhaClient));
            log.info("close channel  [sessionId: {}; userId {}] remove session ", client.getSessionId(), nezhaClient.getUserId());
        }

    }
}
